package cn.gogpay.dcb.api.service;

import cn.gogpay.dcb.api.feign.UserCenterClient;
import cn.gogpay.dcb.common.dto.ResultCode;
import cn.gogpay.dcb.common.dto.ResultDTO;
import cn.gogpay.dcb.common.exception.ServiceException;
import cn.gogpay.dcb.h5base.dto.UserDTO;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * description
 *
 * @author huangting@gogpay.cn
 * @date 2020/1/2 16:56
 */
@Service
public class UserApiService {
    private static final Logger logger = LoggerFactory.getLogger(UserApiService.class);

    @Autowired
    private UserCenterClient userCenterClient;

    /**
     * 获得result 中的数据
     *
     * @param resultDTO
     * @return
     */
    private JSONObject getData(ResultDTO resultDTO) {
        Integer status = resultDTO.getStatus();
        if (ResultCode.SUCCESS_CODE != status) {
            throw new ServiceException(resultDTO.getMsg());
        }
        JSONObject getObj = JSONObject.parseObject(JSONObject.toJSONString(resultDTO));
        return getObj;
    }

    public UserDTO getUserInfo(String userId) {
        ResultDTO resultDTO = userCenterClient.searchUserByUserId(userId);
        logger.info("[{}]用户信息获取请求返回数据，[{}]", userId, resultDTO);
        JSONObject jsonObject = this.getData(resultDTO);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject user = data.getJSONObject("user");
        JSONObject idAuth = user.getJSONObject("idAuth");
        String phone = user.getString("phone");
        String username = user.getString("username");
        UserDTO userDTO = new UserDTO();
        userDTO.setPhoneNo(phone);
        userDTO.setUserId(userId);
        userDTO.setUserName(username);

        if (idAuth != null) {
            String authName = idAuth.getString("authName");
            userDTO.setAuthName(authName);
            String authCardNo = idAuth.getString("authCardNo");
            userDTO.setAuthCardNo(authCardNo);
        }
        return userDTO;
    }
}
